<template>
  <div class="posts-management">
    <div class="header">
      <h2>帖子管理</h2>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="草稿" value="draft" />
          <el-option label="已发布" value="published" />
          <el-option label="已隐藏" value="hidden" />
          <el-option label="已删除" value="deleted" />
          <el-option label="已锁定" value="locked" />
          <el-option label="已封禁" value="banned" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户ID">
        <el-input v-model="searchForm.userId" placeholder="请输入用户ID" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 帖子表格 -->
    <el-table :data="posts" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column prop="user_nickname" label="作者" width="120" />
      <el-table-column prop="status_display" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ row.status_display }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="comments_count" label="评论数" width="80" />
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)">查看</el-button>
          <el-button size="small" @click="handleEditStatus(row)">状态</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 状态编辑对话框 -->
    <el-dialog
      v-model="showEditModal"
      title="编辑帖子状态"
      width="500px"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTagType(currentPost?.status)">
            {{ currentPost?.status_display }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <!-- <el-option label="草稿" value="draft" /> -->
            <el-option label="已发布" value="published" />
            <el-option label="已隐藏" value="hidden" />
            <el-option label="已删除" value="deleted" />
            <el-option label="已锁定" value="locked" />
            <el-option label="已封禁" value="banned" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeEditModal">取消</el-button>
        <el-button type="primary" @click="updatePostStatus" :loading="isUpdating">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/api/request'

const loading = ref(false)
const showEditModal = ref(false)
const isUpdating = ref(false)
const currentPost = ref<any>(null)

const searchForm = reactive({
  status: '',
  userId: ''
})

const editForm = reactive({
  status: ''
})

const posts = ref<any[]>([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'published':
      return 'success'
    case 'draft':
      return 'info'
    case 'hidden':
      return 'warning'
    case 'deleted':
    case 'banned':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取帖子列表
const fetchPosts = async (page = 1) => {
  loading.value = true
  try {
    const params = {
      page: page,
      page_size: pagination.size
    }
    
    // 移除无用的属性赋值
    
    const response = await request.get('/health/posts/', { params })
    posts.value = response.results || []
    pagination.total = response.count || 0
  } catch (error) {
    ElMessage.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchPosts()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, { status: '', userId: '' })
  pagination.current = 1
  fetchPosts()
}

// 查看帖子
const handleView = (row: any) => {
  // 在新窗口中打开帖子详情页
  window.open(`/posts/${row.id}`, '_blank')
}

// 编辑帖子状态
const handleEditStatus = (post: any) => {
  currentPost.value = post
  editForm.status = post.status
  showEditModal.value = true
}

// 关闭编辑弹窗
const closeEditModal = () => {
  showEditModal.value = false
  currentPost.value = null
  editForm.status = ''
}

// 更新帖子状态
const updatePostStatus = async () => {
  if (!currentPost.value) return
  
  isUpdating.value = true
  try {
    const response: any = await request.patch(`/health/posts/${currentPost.value.id}/`, {
      status: editForm.status
    })
    
    // 更新列表中的帖子状态
    const index = posts.value.findIndex((p: any) => p.id === currentPost.value.value?.id)
    if (index !== -1) {
      posts.value[index] = response
    }
    
    ElMessage.success('更新成功')
    closeEditModal()
  } catch (error) {
    ElMessage.error('更新帖子状态失败')
  } finally {
    isUpdating.value = false
  }
}

// 删除帖子
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定删除该帖子吗？此操作会同时删除所有相关评论。', '提示', {
      type: 'warning'
    })
    
    await request.delete(`/health/posts/${row.id}/`)
    ElMessage.success('删除成功')
    fetchPosts()
  } catch (error) {
    // 用户取消删除或删除失败
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.size = val
  fetchPosts()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.current = val
  fetchPosts(val)
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
.posts-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>